package jp.co.ricoh.melody.views.activities;

import android.app.Activity;
import android.content.ComponentName;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.IBinder;
import android.support.v7.app.AppCompatActivity;

import jp.co.ricoh.melody.models.entities.AlarmData;
import jp.co.ricoh.melody.services.AlarmService;
import jp.co.ricoh.melody.utils.LogUtils;
import jp.co.ricoh.melody.views.fragments.AlarmDialogFragment;

/**
 * Copyright (C) 2016 RICOH Co.,LTD.
 * All rights reserved.
 */
public abstract class BaseActivity extends AppCompatActivity
        implements AlarmService.OnAlarmAlertListener, AlarmDialogFragment.OnDismissListener {
    private static final String TAG = BaseActivity.class.getSimpleName();
//    private AlarmDialogFragment mAlarmDialogFragment;
    protected AlarmService mAlarmService;
    private ServiceConnection mServiceConnection = new ServiceConnection() {
        @Override
        public void onServiceConnected(ComponentName componentName, IBinder iBinder) {
            mAlarmService = ((AlarmService.LocalBinder) iBinder).getService();
            mAlarmService.addOnAlarmAlertListener(BaseActivity.this);
            if (mAlarmService.isPlaying()) {
                onAlarmAlert(mAlarmService.getAlarmData());
            }
        }

        @Override
        public void onServiceDisconnected(ComponentName componentName) {
            mAlarmService.removeOnAlarmAlertListener(BaseActivity.this);
            mAlarmService = null;
        }
    };

    @Override
    public void onAlarmAlert(AlarmData alarmData) {
        LogUtils.i(TAG, "onAlarmAlert");
//        attemptDismissAlarmDialog();
//        mAlarmDialogFragment = AlarmDialogFragment.newInstance(alarmData);
//        mAlarmDialogFragment.setOnDismissListener(this);
//        mAlarmDialogFragment.show(getSupportFragmentManager(), null);

    }

    @Override
    public void onDismissFromUser() {
        if (mAlarmService != null) {
            mAlarmService.stopRingtone();
        }
//        attemptDismissAlarmDialog();
    }

//    private void attemptDismissAlarmDialog() {
//        if (mAlarmDialogFragment != null) {
//            try {
//                mAlarmDialogFragment.dismissAllowingStateLoss();
//            } catch (Exception e) {
//                LogUtils.e(TAG, e.getMessage());
//            }
//        }
//    }

    @Override
    protected void onResume() {
        super.onResume();
        Intent service = new Intent(this, AlarmService.class);
        bindService(service, mServiceConnection, Activity.BIND_AUTO_CREATE);
    }

    @Override
    protected void onPause() {
        super.onPause();
        if (mAlarmService != null) {
            mAlarmService.removeOnAlarmAlertListener(this);
        }
        unbindService(mServiceConnection);
    }

}
